<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use app\common\model\Config as ConfigModel;
use app\common\model\BookReturnDetail as BookReturnDetailModel;
use app\common\model\BookAccount as BookAccountModel;
use think\model\concern\SoftDelete;
use think\facade\Log;
use think\Db;

class BookReturn extends Common
{
   // use SoftDelete;
   // protected $deleteTime = 'isdel';
    
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $updateTime = 'draw_date';

    protected $rule = [
        'remark'          => 'require|max:50',
    ];
    protected $msg = [
        'remark.require'  => '请输入退书原因',
        'remark.max'      => '退书原因长度最大50位',
    ];

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }
       
        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('bookreturn')
                        ->field("distinct bookreturn.id,bookreturn.draw_year, case when bookreturn.draw_season = 1 then '春季' when bookreturn.draw_season = 3 then '秋季' end draw_season, pbmdm.bmmc bmmc, pzydm.zymc zymc, pbjdm.bjmc bjmc, case when bookreturn.draw_dir = 1 then '就业' when bookreturn.draw_dir = 2 then '升学' when bookreturn.draw_dir = 3 then '创业' end dirName, bookreturn.draw_dir, bookreturn.xh, pxsdm.xm, bookreturn.draw_remark, mgr.username")
                        ->join('zlzhsf.pbmdm pbmdm', 'bookreturn.draw_bmdm = pbmdm.bmdm', 'left')
                        ->join('zlzhsf.pzydm pzydm', 'bookreturn.draw_zydm = pzydm.zydm', 'left')
                        ->join('zlzhsf.pxsdm pxsdm', 'bookreturn.xh = pxsdm.xh')
                        ->join('zlzhsf.pbjdm pbjdm', 'bookreturn.draw_bjdm = pbjdm.bjdm', 'left')
                        ->join('zl_manage mgr', 'bookreturn.draw_operid = mgr.id', 'left')
                        ->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        
        $listTotal = $this->alias('bookreturn')
                        ->field("distinct bookreturn.id,bookreturn.draw_year, case when bookreturn.draw_season = 1 then '春季' when bookreturn.draw_season = 3 then '秋季' end draw_season, pbmdm.bmmc bmmc, pzydm.zymc zymc, pbjdm.bjmc bjmc, case when bookreturn.draw_dir = 1 then '就业' when bookreturn.draw_dir = 2 then '升学' when bookreturn.draw_dir = 3 then '创业' end dirName, bookreturn.draw_dir, bookreturn.xh, pxsdm.xm, bookreturn.draw_remark, mgr.username")
                        ->join('zlzhsf.pbmdm pbmdm', 'bookreturn.draw_bmdm = pbmdm.bmdm', 'left')
                        ->join('zlzhsf.pzydm pzydm', 'bookreturn.draw_zydm = pzydm.zydm', 'left')
                        ->join('zlzhsf.pxsdm pxsdm', 'bookreturn.xh = pxsdm.xh')
                        ->join('zlzhsf.pbjdm pbjdm', 'bookreturn.draw_bjdm = pbjdm.bjdm', 'left')
                        ->join('zl_manage mgr', 'bookreturn.draw_operid = mgr.id', 'left')
                        ->where($tableWhere['where'])->order($tableWhere['order'])->select();
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = count($listTotal);
        $re['data'] = $data;

        return $re;
    }

    /**
     *  明细
     * User:tony
     * @param $data
     * @return array
     */
    public function getBookDetail($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $where = [];
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['return.id', 'eq', $post['id']];
        }
  
        $list = $this->field("case when detail.type = 'extra' then '非计划发书' when detail.type = 'plan' then '计划发书' end type, detail.book_num, detail.book_price, detail.book_disc, bookInfo.book_name, bookInfo.book_author, bookInfo.book_concern, bookInfo.book_edition, bookInfo.book_isbn, bookInfo.book_reward, bookInfo.book_date")
            ->alias('return')
            ->join('zl_book_return_detail detail', 'return.id = detail.return_id')
            ->join('zl_book_info bookInfo', 'detail.book_id = bookInfo.id') 
            ->where($where)
            ->order('detail.type, detail.book_id')
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    /**
     *  退书
     * User:wanglu
     * @param $data
     * @return array
     */
    public function bookReturn($data)
    {
        $return = [
            'status' => false,
            'msg'    => '退书失败',
            'data'   => ''
        ];

        // 变量
        $xh = $data['xh'];
        $books = $data['books'];
        $remark = $data['remark'];
        $operid = session('manage')['id'];
        $list       = explode(",", $books);

        $config = new ConfigModel();
        $data = input('param.');
        $year = $config->getYear();
        $season = $config->getSeason();

        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 

        // 首先要判断该学生是否存在跨专业领书的情况
        // 未跨专业生成一条记录
        // 跨专业领书，计划生成一条记录，非计划生成一条记录
        // 保存明细
        $groupData = [];
        foreach($list as $val) {
            $valList  = explode(";", $val);
            $type = $valList[0];
            $xh = $valList[1];
            $book_id = $valList[2];
            $book_num = $valList[3];
            $book_price = $valList[4];
            $book_disc = $valList[5];
            $item = [
                'return_id'   => '',
                'type'        => $type,
                'book_id'     => $book_id,
                'book_num'    => $book_num,
                'book_price'  => $book_price,
                'book_disc'  => $book_disc,
            ];

            // 获取组织架构信息
            $sql = "";
            if($type == "plan") {
                $sql = "select draw_dep_id bmdm, draw_specialty_id zydm, b.bjdm, draw_grade grade, draw_dir dir 
                    from zl_book_draw a left join 
                    zl_plan_student_rel b on a.draw_class_id = b.plan_code
                    where xh = '".$xh."' and draw_year = ".$year." and draw_season = ".$season;
            } else if($type == "extra") {
                $sql = "select DISTINCT a.dep_id bmdm, b.zydm, b.bjdm, a.grade, c.dir
                    From zl_book_extra_draw a left join 
                    zl_book_extra_draw_detail b on a.id = b.draw_id left join 
                    zl_cw_struct_cache c on b.bjdm = c.bjdm and b.dir = c.dir left join
                    zl_student_type_book_rel d on a.type_id = d.type_id and a.param_id = d.param_id and plan_year = ".$year." and plan_season = ".$season."
                    where b.xh = '".$xh."' and year = ".$year." and season = ".$season." and d.book_id in(".$book_id.")";
            } 
            $list = Db::query($sql);
            if (!$list || count($list) == 0) {
                $return['msg'] = "未查询到教材发放记录";
                return $return;
            }

            // 保存
            $key = $list[0]['bmdm']."_".$list[0]['zydm']."_".$list[0]['bjdm']."_".$list[0]['grade']."_".$list[0]['dir'];
            
            if (array_key_exists($key, $groupData)) {
                $groupData[$key]['items'][] = $item;
            } else {
                $groupData[$key]['bmdm'] = $list[0]['bmdm'];
                $groupData[$key]['zydm'] = $list[0]['zydm'];
                $groupData[$key]['bjdm'] = $list[0]['bjdm'];
                $groupData[$key]['grade'] = $list[0]['grade'];
                $groupData[$key]['dir'] = $list[0]['dir'];
                $groupData[$key]['items'][] = $item;
            } 
        }

        Db::startTrans();
        foreach($groupData as $returnItem) {
            $new_id = $this->getMaxID();  // 最新ID
            // 保存主表
            $iData       = [
                'id'                => $new_id,
                'draw_operid'       => $operid,
                'draw_year'         => $year,
                'draw_season'       => $season,
                'draw_school_id'    => '',
                'draw_institute_id' => '',
                'draw_bmdm'         => $returnItem['bmdm'],
                'draw_zydm'         => $returnItem['zydm'],
                'draw_bjdm'         => $returnItem['bjdm'],
                'draw_grade'        => $returnItem['grade'],
                'draw_dir'          => $returnItem['dir'],
                'xh'                => $xh,
                'draw_date'         => time(),
                'draw_remark'       => $remark
            ];
            $this->insert($iData);

            $itemData = [];            
            foreach($returnItem['items'] as $val) {
                $val['return_id'] = $new_id;
                $itemData[] = $val;
            }

            Log::Info($itemData);
            // 保存明细表
            $bookReturnDetailModel = new BookReturnDetailModel();
            if (!$bookReturnDetailModel->saveAll($itemData)) {
                $result['status'] = false;
                $result['msg'] = '退书明细提交失败，请重试';
                Db::rollback();
                return $result;
            } 
        }

        Db::commit();
        // 设置账表状态
        // $bookAccountModel = new BookAccountModel();
        // $bookAccountModel->save(['status'=>0], ['year'=>$year, 'season'=>$season, 'xh'=>$xh]);
        
        $return['data']   = [];
        $return['status'] = true;
        $return['msg']    = '退书成功'; 
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $return;
    }
     
    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['draw_year', '=', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['draw_season', '=', $post['season']];
        }
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['bookreturn.xh', '=', $post['xh']];
        }
        if(isset($post['xm']) && $post['xm'] != ""){
            $where[] = ['pxsdm.xm', 'like', '%'.$post['xm'].'%'];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['bookreturn.draw_bmdm', '=', $post['dep_id']];
        }
        if(isset($post['specialty_id']) && $post['specialty_id'] != ""){
            $where[] = ['bookreturn.draw_zydm', '=', $post['specialty_id']];
        }
        if(isset($post['class_id']) && $post['class_id'] != ""){
            $where[] = ['bookreturn.draw_bjdm', '=', $post['class_id']];
        }
        if(isset($post['draw_remark']) && $post['draw_remark'] != ""){
            $where[] = ['draw_remark', 'like', '%'.$post['draw_remark'].'%'];
        }
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['bookreturn.id', 'eq', $post['id']];
        }
        
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['bookreturn.id ASC'];
        return $result;
    }


    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach($list as &$val){
           
            $val['draw_date'] = getTime($val['draw_date']);
        }
        return $list;
    }

    // 获取最新的id
    public function getMaxID()
    {
        $pre_id = date("Ymd");  # 编号前缀
        $condition = [['id', "like",  $pre_id."%"]];  # 必须是二维数组
        $res = $this->where($condition)->max('id');
        if($res){
			$num = (int)substr($res, -4);  # 截取最后4位
            $num++;
			$res = $pre_id.sprintf("%04d", $num);  # 补足4位
        }
        else{
            $res = $pre_id."0001";
        }
        return $res;
    }
}